/**
 * Created by Administrator on 2016/7/11.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'collection',
    'model',
    'dialog',
    'datepicker'
], function ($, common, ready, template, Collection, Model, dialog, datepicker) {

    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            var _this = this;
            loading();
            this.event();

            //分类
            $.ajax({
                url: _global.url.api + 'categorys',
                type: 'get',
                async: false,
                data: {depth: 1},
                success: function (res) {
                    if (res.code == 0) {
                        _this.category = res.data;
                    }
                }
            });

            this.fetch();
        },

        fetch: function (_args) {
            var args = _args || {};
            args.limit = 10;
            args.offset = 0;
            var _this = this;
            this.collection = new Collection({
                container: 'data-list',
                template: 'data-item',
                url: _global.url.api + 'agent/Gh',
                condition: args,
                model: {
                    tag_name: 'tr',
                    url: {
                        put: _global.url.api + 'site/{id}'
                    },
                    event: {
                        '.item-online:click': 'online',
                        '.item-offline:click': 'offline',
                        '.item-memo:click': 'memo',
                        '.item-assign': 'assign',
                        '.item-cancel-assign': 'cancelAssign',
                        '.item-reset-pwd': 'resetPwd',
                        '.item-sz': 'viewAttachment',
                        '.item-over-to:click': 'overTo'
                    },
                    online: function (e) {
                        e.preventDefault();
                        var _this = this;
                        $.ajax({
                            url: _global.url.api + 'site/online/' + this.get_data('id'),
                            type: 'put',
                            success: function (res) {
                                if (res.code == 0) {
                                    _this.data.status = 1;
                                    _this.create_element();
                                }
                            },
                            error: function () {
                                Alert({msg: '通讯错误', type: 'error'});
                            }
                        });
                    },
                    offline: function (e) {
                        e.preventDefault();
                        var _this = this;
                        $.ajax({
                            url: _global.url.api + 'site/offline/' + this.get_data('id'),
                            type: 'put',
                            success: function (res) {
                                if (res.code == 0) {
                                    _this.data.status = 2;
                                    _this.create_element();
                                }
                            },
                            error: function () {
                                Alert({msg: '通讯错误', type: 'error'});
                            }
                        });
                    },
                    memo: function (e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            content: template('memo-tpl', {memo: this.data.memo}),
                            ok: function () {
                                model.formData = {memo: $('textarea[name="memo"]').val()};
                                model.put();
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    assign: function (e) {
                        e.preventDefault();
                        var model = this;
                        var admins = _this.getAdmins();
                        $.each(admins, function (ind, item) {
                            item.assigned = false;
                            $.each(model.get_data('admins'), function (n, v) {
                                if (item.id == v.id) {
                                    item.assigned = true
                                }
                            });
                        });

                        dialog({
                            content: template('assign-tpl', {admins: admins}),
                            width: 200,
                            ok: function () {
                                var admin_ids = $('[name="admin_id"]').val();
                                new Model({
                                    url: _global.url.api + 'assign_site',
                                    data: {
                                        admin_id: admin_ids,
                                        site_id: model.get_data('id')
                                    }
                                }).post();
                                _this.collection.reload();

                            }, cancel: function () {
                            }
                        }).show();
                    },
                    cancelAssign: function (e) {
                        var model = this;
                        e.preventDefault();
                        var admin_id = $(e.currentTarget).attr('rel');
                        new Model({
                            url: _global.url.api + 'assign_site',
                            data: {
                                admin_id: admin_id,
                                site_id: model.get_data('id')
                            }
                        }).del();
                        _this.collection.reload();
                    },
                    resetPwd: function (e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            content: '将此账号密码重置为1234567,是否继续？',
                            ok: function () {
                                $.ajax({
                                    url: _global.url.api + 'site/reset_password',
                                    type: 'put',
                                    data: {id: model.get_data('id')},
                                    success: function (res) {
                                        if (res.code == 0) {
                                            Alert({msg: '密码重置成功'});
                                        } else {
                                            Alert({msg: res.msg, type: 'error'});
                                        }
                                    }, error: function () {
                                        Alert({msg: '通讯失败', type: 'error'});
                                    }
                                });
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    viewAttachment: function (e) {
                        e.preventDefault();
                        dialog({
                            content: template('sz-tpl', this.get_data('certs')),
                            width: 500,
                            ok: function () {
                            }
                        }).show();
                    },
                    overTo: function(e) {
                        e.preventDefault();
                        var model = this;
                        dialog({
                            'content': '确定转入名下吗?',
                            ok: function() {
                                $.ajax({
                                    url: _global.url.api + 'agent/over_to',
                                    type: 'put',
                                    data: {id: model.get_data('id')},
                                    success: function (res) {
                                        if (res.code == 0) {
                                            Alert({msg: '成功转入名下'});
                                        } else {
                                            Alert({msg: res.msg, type: 'error'});
                                        }
                                    }, error: function () {
                                        Alert({msg: '通讯失败', type: 'error'});
                                    }
                                });
                            }, cancel: function() {}
                        }).show(e.target);
                    },
                    change: function (e) {
                        this.data[$(e.target).attr('name')] = $(e.target).val();
                    }
                },
                callback: function () {
                    loaded();
                }
            });
            this.collection.fetch();
            this.showCategory();
        },

        showCategory: function () {
            var _this = this;
            //一级分类
            $.each(_this.category, function (n, v) {
                if (v.pid == null) {
                    $('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                }
            });
            //显示二级分类，并联动
            //bind change event
            $('[name="cate"]').on('change', function () {
                var id = $(this).val();
                $('[name="child-cate"]').hide();

                $('[name="child-cate"]').html('<option value="0">所有小类</option>').show();
                $.ajax({
                    url: _global.url.api + 'categorys',
                    type: 'get',
                    async: false,
                    data: {depth: 1, pid: id},
                    success: function (res) {
                        if (res.code == 0) {
                            $.each(res.data, function (n, v) {
                                $('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                            });
                        }
                    }
                });
            });
        },

        getAdmins: function () {
            var _this = this;
            if (typeof this.admins !== 'undefined') {
                return this.admins;
            }
            this.admins = [];
            $.ajax({
                url: _global.url.api + 'admins',
                type: 'get',
                async: false,
                data: {limit: 200},
                success: function (res) {
                    if (res.code == 0) {
                        _this.admins = res.data;
                    }
                }
            });
            return this.admins;
        },

        event: function () {
            var _this = this;
            $('.long_date').on('click', function () {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd'
                });
            });
            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.type = $("#type").val();
                _this.collection.condition.start_time = $('input[name="begintime"]').val();
                _this.collection.condition.end_time = $('input[name="endtime"]').val();
                _this.collection.reload();
            });

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = '';
                _this.collection.condition.status = $(e.target).attr('rel');
                _this.collection.condition.type = $("#type").val();
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });

            $('#btn-batch-assign').on('click', function (e) {
                e.preventDefault();
                var site_ids = [];
                $.each($('[name="site_id"]:checked'), function () {
                    site_ids.push($(this).val());
                });
                if (site_ids.length === 0) {
                    Alert({msg: '请选择需要指派的站点', type: 'error'});
                    return;
                }
                var admins = _this.getAdmins();
                $.each(admins, function (ind, item) {
                    item.assigned = false;
                    $.each(_this.collection.models, function (n, model) {
                        $.each(model.get_data('admins'), function (n, v) {
                            if (item.id == v.id) {
                                item.assigned = true
                            }
                        });
                    });
                });
                dialog({
                    content: template('assign-tpl', {admins: admins}),
                    width: 200,
                    ok: function () {
                        var admin_ids = $('[name="admin_id"]').val();
                        new Model({
                            url: _global.url.api + 'batch_assign_site',
                            data: {
                                admin_id: admin_ids,
                                site_id: site_ids
                            }
                        }).post();
                        _this.collection.reload();

                    }, cancel: function () {
                    }
                }).show();
            });
        },

        change: function (e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        }

    };

    new index();

});